package com.learn.rabbitmq.three;

import com.learn.rabbitmq.utils.RabbitMqUtils;
import com.learn.rabbitmq.utils.SleepUtils;
import com.rabbitmq.client.Channel;

import java.nio.charset.StandardCharsets;

/**
 * 消息在手动应答时不丢失、放回队列中重新消费
 */
public class Worker3 {

    public static final String TASK_QUEUE_NAME = "ack_queue";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMqUtils.getChannel();
        System.out.println("C2等待接收信息处理 沉睡时间长");

        //设置不公平分发
        //channel.basicQos(1);//默认0

        //设置预取值
        channel.basicQos(2);//默认0
        boolean autoAck=false;
        //采用手动应答
        channel.basicConsume(
            TASK_QUEUE_NAME,
            autoAck,
            (consumerTag, message) -> {
                //沉睡1s
                SleepUtils.sleep(30);
                //接收消息处理
                System.out.println(new String(message.getBody(), StandardCharsets.UTF_8));
                //手动应答
                /**
                 * 1.消息的标记TAG
                 * 2.是否批量应答 false:不批量应答信道中的消息
                 */
                channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
            },
            consumerTag -> {
                System.out.println("消息取消处理");
            });
    }

}
